package server.impl;

import clients.MessageClient;
import message.Message;
import server.MessageServer;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认的通信服务，支持三端通信
 */
public class DefaultMessageServer implements MessageServer {

    public Map<String, MessageClient> clients = new ConcurrentHashMap<>();

    public DefaultMessageServer() {
        System.out.println("创建服务器");
    }

    @Override
    public int sendMessage(Message message) {
        Collection<MessageClient> values = clients.values();
        int successful = 0;
        for (MessageClient value : values) {
            boolean success = value.receiveMessage(message);
            if (success) {
                successful++;
            }
        }
        return successful;
    }

    @Override
    public boolean join(MessageClient client) {
        Map<String, MessageClient> c = this.clients;
        c.put(client.getId(), client);
        System.out.println("有人加入: " + client.toString());
        return true;
    }
}
